package com.serenegiant.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

import java.text.SimpleDateFormat;
import java.util.Date;

public class BitmapUtils {

    /**
     * 添加时间水印
     *
     * @param mBitmap
     * @return
     */
    public static Bitmap addTimeWatermark(Bitmap mBitmap) {
        //获取原始图片与水印图片的宽与高
        int mBitmapWidth = mBitmap.getWidth();
        int mBitmapHeight = mBitmap.getHeight();
        Bitmap mNewBitmap = Bitmap.createBitmap(mBitmapWidth, mBitmapHeight, Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(mNewBitmap);
        //向位图中开始画入MBitmap原始图片
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
        //添加文字
        Paint mPaint = new Paint();
        String dataStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EEEE").format(new Date());
        mPaint.setColor(Color.RED);
        mPaint.setTextSize(20);
        //水印的位置坐标
        mCanvas.drawText("简明信息 " + dataStr, (mBitmapWidth * 1) / 10, (mBitmapHeight * 14) / 15, mPaint);
        mCanvas.save(Canvas.ALL_SAVE_FLAG);
        mCanvas.restore();

        return mNewBitmap;
    }

    /**
     * 将图片转为bitmap
     *
     * @param res
     * @param id
     * @param opts
     * @return
     */
    public static Bitmap getBitmap(Resources res, int id, BitmapFactory.Options opts) {
        Bitmap bitmap = BitmapFactory.decodeResource(res, id, opts);
        return bitmap;
    }

    /**
     * 叠加两张图片
     *
     * @param background 背景图片
     * @param foreground 前置图片
     * @return
     */
    public static Bitmap toConformBitmap(Bitmap background, Bitmap foreground) {
        if (background == null) {
            return null;
        }

        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        //create the new blank bitmap 创建一个新的和SRC长度宽度一样的位图
        Bitmap newBmp = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBmp);
        //draw bg into 在 0，0坐标开始画入bg
        canvas.drawBitmap(background, 0, 0, null);
        //draw fg into 在 0，0坐标开始画入fg ，可以从任意位置画入
        canvas.drawBitmap(foreground, 0, 0, null);
        //save all clip 保存
        canvas.save(Canvas.ALL_SAVE_FLAG);
        //stor 存储
        canvas.restore();
        return newBmp;
    }
}
